#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=95

disable_gro_gso() {
	which ethtool &>/dev/null || return 0
	for eth in $(ifconfig | grep "^eth\|^dsa" | awk '{print $1}' | sort | uniq); do
		ethtool -k "$eth" | grep -q "generic-receive-offload: off" || {
			ethtool -K "$eth" gro off
			logger -t natflow "disable gro for <$eth>"
		}
		ethtool -k "$eth" | grep -q "generic-segmentation-offload: off" || {
			ethtool -K "$eth" gso off
			logger -t natflow "disable gso for <$eth>"
		}
	done
}

start() {
	test -c /dev/natflow_ctl || return 0
	disable_gro_gso
	hwnat_wed=$(uci get natflow.main.hwnat_wed 2>/dev/null || echo 0)
	hwnat=$(uci get natflow.main.hwnat 2>/dev/null || echo 0)
	enabled=$(uci get natflow.main.enabled 2>/dev/null || echo 0)
	debug=$(uci get natflow.main.debug 2>/dev/null || echo 3)
	delay_pkts=$(uci get natflow.main.delay_pkts 2>/dev/null || echo 0)
	skip_qos_to_slow_path=$(uci get natflow.main.skip_qos_to_slow_path 2>/dev/null || echo 0)
	ifname_filter=$(uci get natflow.main.ifname_filter 2>/dev/null)

	echo "debug=$debug" >/dev/natflow_ctl
	echo "disabled=$((!enabled))" >/dev/natflow_ctl
	grep -q "hwnat=" </dev/natflow_ctl && echo "hwnat=$hwnat" >/dev/natflow_ctl
	grep -q "hwnat_wed_disabled=" </dev/natflow_ctl && echo "hwnat_wed_disabled=$((!hwnat_wed))" >/dev/natflow_ctl
	if [ "${hwnat_wed}" = "1" ]; then
		for p in /sys/module/*/parameters/wed_enable; do
			test -e "$p" && echo Y >"$p"
		done
	else
		for p in /sys/module/*/parameters/wed_enable; do
			test -e "$p" && echo N >"$p"
		done
	fi

	echo "delay_pkts=$delay_pkts" >/dev/natflow_ctl
	echo "skip_qos_to_slow_path=$skip_qos_to_slow_path" >/dev/natflow_ctl
	echo ifname_clear >/dev/natflow_ctl
	for ifn in ${ifname_filter}; do
		echo "ifname_add=$ifn" >/dev/natflow_ctl
	done
}

stop() {
	test -c /dev/natflow_ctl || return 0
	echo disabled=1 >/dev/natflow_ctl
}

restart() {
	start
}
